package spring.cloud.tasks.executor.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.task.TaskExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Setter
@Getter
public class ExecutorIdToTaskIdToTaskExecutorMapMap {

    private static Map<String, ConcurrentHashMap<String, TaskExecutor>> executorIdToTaskIdToTaskExecutorMapMap = new ConcurrentHashMap<>();

    private ExecutorIdToTaskIdToTaskExecutorMapMap() {
    }

    public static Map<String, ConcurrentHashMap<String, TaskExecutor>> getExecutorIdToTaskIdToTaskExecutorMapMap() {
        return executorIdToTaskIdToTaskExecutorMapMap;
    }

    /**
     * 添加作业控制器.
     */
    public static void addTaskExecutor(final String executorId, final String taskId, final TaskExecutor taskExecutor) {
        if (executorIdToTaskIdToTaskExecutorMapMap.containsKey(executorId)) {
            executorIdToTaskIdToTaskExecutorMapMap.get(executorId).put(taskId, taskExecutor);
        } else {
            ConcurrentHashMap<String, TaskExecutor> taskIdToTaskExecutorMap = new ConcurrentHashMap<>();
            taskIdToTaskExecutorMap.put(taskId, taskExecutor);
            executorIdToTaskIdToTaskExecutorMapMap.put(executorId, taskIdToTaskExecutorMap);
        }
    }

    public static void removeTaskExecutor(String executorId) {
        executorIdToTaskIdToTaskExecutorMapMap.remove(executorId);
    }

    public static void removeTaskExecutor(String executorId, String taskId) {
        Map<String, TaskExecutor> taskIdToTaskExecutorMap = executorIdToTaskIdToTaskExecutorMapMap.get(executorId);
        if (taskIdToTaskExecutorMap != null) {
            taskIdToTaskExecutorMap.remove(taskId);
        }
    }

}
